package com.shenyue.nbtownlet.model;

import android.content.Context;

import com.alibaba.fastjson.JSONObject;
import com.shenyue.nbtownlet.event.BaseListener;
import com.shenyue.nbtownlet.util.SecurityUtil;
import com.shenyue.nbtownlet.util.StringUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.GetBuilder;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.request.RequestCall;

import java.util.Iterator;
import java.util.Map;

import okhttp3.Call;

public class NbzjClientExManager {
    private static NbzjClientExManager instance;
    private static final String CUSTOMER_ID = "customerid";

    protected NbzjClientExManager() {
    }

    public static NbzjClientExManager instance() {
        if (instance == null) {
            instance = new NbzjClientExManager();
        }
        return instance;
    }

    public RequestCall post(Context context, String server, final String action, JSONObject param, final BaseListener listener) {
        try {
            PostFormBuilder builder = OkHttpUtils.post();
            builder.url(server);
            if (param != null) {
                Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, Object> entry = it.next();
                    String value = StringUtil.getValue(entry.getValue());
                    builder.addParams(entry.getKey(), value);
                }
            }
            if(!StringUtil.isNull(AppLoginModel.getIdentityId(context)))
                builder.addHeader(CUSTOMER_ID, AppLoginModel.getIdentityId(context));
            long security_timestamp = SecurityUtil.getTimestamp();
            builder.addParams("security_timestamp", String.valueOf(security_timestamp));

            String token = SecurityUtil.getToken(AppModel.APPKEY, AppModel.SECRETKEY, security_timestamp);
            builder.addParams("security_token", token);

            RequestCall call = builder.build();
            call.execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    String message = e.getMessage();
                    if (message.contains("401"))
                        listener.error("会话过期，请重新登录", action);
                    else if (message.contains("500"))
                        listener.error("服务连接失败，请稍候再试", action);
                    else if (message.contains("501"))
                        listener.error("用户名或密码错误", action);
                    else
                        listener.error("发送网络请求出错..., 请稍候再试", action);
                }

                @Override
                public void onResponse(String response, int id) {
                    try {
                        listener.success(response, action);
                    } catch (Exception e) {
                        listener.error("数据解析出错！", action);
                    }
                }
            });
            return call;
        } catch (Exception e) {
            listener.error(e.getMessage(), action);
        }
        return null;
    }

    public RequestCall get(Context context, String server, final String action, JSONObject param, final BaseListener listener) {
        try {
            GetBuilder builder = OkHttpUtils.get();
            builder.url(server);
            if (param != null) {
                Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, Object> entry = it.next();
                    String value = StringUtil.getValue(entry.getValue());
                    builder.addParams(entry.getKey(), value);
                }
            }
            if(!StringUtil.isNull(AppLoginModel.getIdentityId(context)))
                builder.addHeader(CUSTOMER_ID, AppLoginModel.getIdentityId(context));
            long security_timestamp = SecurityUtil.getTimestamp();
            builder.addParams("security_timestamp", String.valueOf(security_timestamp));

            String token = SecurityUtil.getToken(AppModel.APPKEY, AppModel.SECRETKEY, security_timestamp);
            builder.addParams("security_token", token);

            RequestCall call = builder.build();
            call.execute(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    String message = e.getMessage();
                    if (message.contains("401"))
                        listener.error("会话过期，请重新登录", action);
                    else if (message.contains("500"))
                        listener.error("服务连接失败，请稍候再试", action);
                    else if (message.contains("501"))
                        listener.error("用户名或密码错误", action);
                    else
                        listener.error("发送网络请求出错..., 请稍候再试", action);
                }

                @Override
                public void onResponse(String response, int id) {
                    try {
                        listener.success(response, action);
                    } catch (Exception e) {
                        listener.error("数据解析出错！", action);
                    }
                }
            });
            return call;
        } catch (Exception e) {
            listener.error(e.getMessage(), action);
        }
        return null;
    }
}
